﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace InteratorStudy
{
    public class SampleCollection : IEnumerable
    {
        public int[] items;
        public SampleCollection()
        {
            items = new int[] { 5, 4, 6, 9, 2 };
        }

        public IEnumerable BuilderCollection()
        {
            for (int i = 0; i < items.Length; i++)
            {
                yield return items[i];
            }
        }

        #region IEnumerable 成员
        //1.使用yeild实现的枚举接口
        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < items.Length; i++)
            {
                yield return items[i];
            }
        }

        ////2.自己实现的枚举接口
        //public IEnumerator GetEnumerator()
        //{
        //    return new SampleEnumerator(this.items);
        //}



        #endregion

        #region IEnumerable<int> 成员
        //3.另外还可以考虑使用 泛型枚举器的方式实现，其性能会更高
        public IEnumerable<int> GenericInterator()
        {
            for (int i = 0; i < items.Length; i++)
            {
                yield return items[i];
            }
        }

        #endregion

        #region IEnumerable 成员

        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    public class SampleEnumerator : IEnumerator
    {
        public int[] items;
        int position = -1;

        public SampleEnumerator(int[] items)
        {
            this.items = items;
        }



        #region IEnumerator 成员

        public object Current
        {
            get
            {
                if (position == -1)
                {
                    return null;
                }
                else
                {
                    if (position >= items.Length)
                    {
                        return null;
                    }
                    else
                    {
                        return items[position];
                    }
                }
            }
        }

        public bool MoveNext()
        {
            if (position + 1 >= items.Length)
            {
                return false;
            }
            else
            {
                position++;
                return true;
            }
        }

        public void Reset()
        {
            position = -1;
        }

        #endregion
    }
}
